package com.guli.eduService.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guli.eduService.entity.EduSubject;
import com.guli.eduService.entity.excel.SubjectData;
import com.guli.eduService.service.EduSubjectService;
import com.guli.servicebase.exceptionhandler.GuliException;

/**
 * 读取excel的监听器
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public EduSubjectService subjectService;

    public SubjectExcelListener() {
    }

    //将service进行手动注入
    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectData data, AnalysisContext context) {
        if (data == null) {
            throw new GuliException(20001, "文件中没有数据");
        }
        //判断分类是否重复
        EduSubject oneSubject = existOneSubject(subjectService, data.getOneSubjectName());
        if (oneSubject == null) { //不存在则添加
            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(data.getOneSubjectName());
            subjectService.save(oneSubject);
        }
        String pid = oneSubject.getId();

        EduSubject twoSubject = existTwoSubject(subjectService, data.getTwoSubjectName(), pid);
        if (twoSubject == null) { //不存在则添加
            twoSubject = new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(data.getTwoSubjectName());
            subjectService.save(twoSubject);
        }
    }

    //判断一级分类不能重复添加
    public EduSubject existOneSubject(EduSubjectService subjectService, String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        EduSubject result = subjectService.getOne(wrapper);
        return result;
    }

    //判断二级分类不能重复添加
    public EduSubject existTwoSubject(EduSubjectService subjectService, String name, String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        EduSubject result = subjectService.getOne(wrapper);
        return result;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}